<?php

function statName($status){
	$val = "";
	switch ($status){
		case 1 :
			$val = "Akan produksi";
			break;
		case 2 :
			$val = "Akan kirim";
			break;
		case 3 :
			$val = "Sudah kirim";
			break;
		default : break;
	}
	return $val;
}

function checkSender($config,$sender){
	$idc = 0;
	$db =  new db($config);
	$result = $db->query("SELECT idCrew FROM mn_crew WHERE twitter='$sender'");
	if ($result && $db->rowCount() > 0) {
		$idc = $result[0]['idCrew'];
	}
	return $idc;
}

function checkCusto($config,$nohp){
	$idc = 0;
	$db =  new db($config);
	$nohp = substr($nohp, 1);
	$result = $db->query("SELECT idCustomer FROM mn_customer WHERE no_hape='$nohp'");
	if ($result && $db->rowCount() > 0) {
		$idc = $result[0]['idCustomer'];
	}
	return $idc;
}

function getCust($config,$idc){
	$retval = NULL;
	$db =  new db($config);
	$result = $db->query("SELECT * FROM mn_customer WHERE idCustomer='$idc'");
	if ($result && $db->rowCount() > 0) {
		$retval = $result[0];
	}
	return $retval;
}

function getHPSender($config,$idsender){
	$retval = '';
	$db =  new db($config);
	$result = $db->query("SELECT no_hape FROM mn_crew WHERE twitter='$idsender'");
	if ($result && $db->rowCount() > 0) {
		$retval = '0'.$result[0]['no_hape'];
	}
	return $retval;
}

function getInfoProd($config){
	$retval = '';
	$db =  new db($config);
	$result = $db->query("SELECT SUM(qty) as total FROM mn_embozz WHERE status = '1'");
	if ($result && $db->rowCount() > 0) {
		$retval = $result[0]['total'];
	}
	return $retval;
}

function getInfoPesanan($config,$nopes){
	$retval = NULL;
	$db =  new db($config);
	$result = $db->query("SELECT * FROM mn_embozz WHERE idEmbozz = '$nopes'");
	if ($result && $db->rowCount() > 0) {
		$retval = $result[0];
	}
	return $retval;
}

function kirimPesan($ukey,$pkey,$nomor,$pesan){
	$url = 'http://zenziva.com/apps/smsapi.php?userkey='.$ukey.'&passkey='.$pkey.'&nohp='.$nomor.'&pesan='.urlencode($pesan);
	$curlHandle = curl_init();
	curl_setopt($curlHandle, CURLOPT_URL, $url);
	//curl_setopt($curlHandle, CURLOPT_HEADER, 0);
	curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curlHandle, CURLOPT_USERAGENT, 'Codular Sample cURL Request');
	curl_setopt($curlHandle, CURLOPT_TIMEOUT,30);
	$results = curl_exec($curlHandle);
	curl_close($curlHandle);
}

function controller_api($config) {
	$consumer_key = '0olrhorFsUlvefRtPyow';
	$consumer_secret = 'ZLat0B7JpdxaihMxHXmmCDYWHLNhZdKKd96sfGssf4M';
	$oauth_token = '385766335-BaVHLjSzGmN7CgslXChR59eQUX7nWWeFJRIcJ3qg';
	$oauth_token_secret = 'JMzrKjCCgSOCcXvoFfUfMi11OHZ2Rm4tx1XO7LKw8k';
	//
	$ukey = "nbga3t";
	$pkey = "t3agbn";
    if ((isset($config['ruri'][1])) && ($config['ruri'][1]=='get') && (isset($config['ruri'][2])) && ($config['ruri'][2]=='direct_messages')){
		//../get/messages
		$twitter = new TwitterOAuth(
			$consumer_key,
			$consumer_secret,
			$oauth_token,
			$oauth_token_secret
		);
		$content = $twitter->get('account/verify_credentials');	//verify token
		$responses = $twitter->get('direct_messages');
		foreach ($responses as $response => $obj){
			echo $obj->id_str."-";
			$idm = $obj->id_str;
			//var_dump($obj->entities->hashtags[0]->text)."-";
			//var_dump($obj->entities->hashtags[1]->text)."-";
			//echo $obj->sender->screen_name."-";
			$sender = $obj->sender->screen_name;
			//echo $obj->created_at."-";
			//echo $obj->text;
			$msg = $obj->text;
			$amsg=explode(' ',$msg);
			if (isset($obj->entities->hashtags[0]) && isset($obj->entities->hashtags[1]) && ($obj->entities->hashtags[0]->text=='embozz')){
				//perintah untuk embozz
				switch($obj->entities->hashtags[1]->text){
					case 'pesan' :	//1
						$nohp = $amsg[2];
						$qty = $amsg[3];
						//cek boleh gak
						$idsender = checkSender($config,$sender);
						$idcust = checkCusto($config,$nohp);
						if (($idsender>0)&&($idcust>0)){
							$ret = getCust($config,$idcust);
							$nama = $ret['nama'];
							$prov = $ret['prov'];
							$kota = $ret['kabkot'];
							$alamat = $ret['alamat'];
							$kodepos = $ret['kodepos'];
							$db =  new db($config);
							$tgl = date('Y-m-d H:i:s', time());
							$embozz ="INSERT INTO `mn_embozz` (`idCust` ,`nama` ,`qty` ,`prov` ,`kabkot` ,`alamat` ,`kodepos` ,`tgl_pesan` ,`status` ,`modifier`) VALUES ('$idcust', '$nama', '$qty', '$prov', '$kota', '$alamat', '$kodepos', '$tgl', '1', '$idsender');";
							//echo $embozz;
							$db->exec($embozz);
							$nopes = $db->lastInsertId();
							//KIRIM DM
							$teks = "SUKSES : tambah pesanan #$nopes a.n '$nama'.";
						}else{
							//kirim tanda salah
							$teks = "GAGAL : tambah pesanan #$nopes a.n '$nama'.";
						}
						//KIRIM DM
						$content = $twitter->get('account/verify_credentials');	//verify token
						$resp = $twitter->post('direct_messages/new',array('text'=>$teks,'screen_name'=>$sender));
						//KIRIM TWIT
						//$teks = $teks." @$sender";
						//$resp = $twitter->post('statuses/update',array('status'=>$teks));
						//KIRIM SMS
						$nohp = getHPSender($config,$sender);
						if ($nohp==''){}else{
							kirimPesan($ukey,$pkey,$nohp,$teks);
						}
						break;
					case 'jadi' :	//2
						$nopes = $amsg[2];
						$db =  new db($config);
						$que = "UPDATE mn_embozz SET status = '2' WHERE idEmbozz = '$nopes'";
						//echo $que;
						$db->exec($que);
						$teks = "SUKSES : ubah status pesanan #$nopes.";
						//DM
						$content = $twitter->get('account/verify_credentials');	//verify token
						$resp = $twitter->post('direct_messages/new',array('text'=>$teks,'screen_name'=>$sender));
						//SMS
						$nohp = getHPSender($config,$sender);
						if ($nohp==''){}else{
							kirimPesan($ukey,$pkey,$nohp,$teks);
						}
						break;
					case 'kirim' :	//3
						$nopes = $amsg[2];
						$db =  new db($config);
						$que = "UPDATE mn_embozz SET status = '3' WHERE idEmbozz = '$nopes'";
						//echo $que;
						$db->exec($que);
						$teks = "SUKSES : ubah status pesanan #$nopes.";
						//DM
						$content = $twitter->get('account/verify_credentials');	//verify token
						$resp = $twitter->post('direct_messages/new',array('text'=>$teks,'screen_name'=>$sender));
						//SMS
						$nohp = getHPSender($config,$sender);
						if ($nohp==''){}else{
							kirimPesan($ukey,$pkey,$nohp,$teks);
						}
						break;
					case 'infoproduksi' :
						$idsender = checkSender($config,$sender);
						if ($idsender>0){
							$nohp = getHPSender($config,$sender);
							echo $nohp;
							if ($nohp==''){}else{
								$tot = getInfoProd($config);
								$pesan = "Kita kurang produksi embozz sebanyak $tot buah";
								kirimPesan($ukey,$pkey,$nohp,$pesan);
							}
						}
						break;
					case 'cekpesanan' :
						$nopes = $amsg[2];
						$infopes = getInfoPesanan($config,$nopes);
						$alamat = $infopes['alamat'];
						$idc = $infopes['idCust'];
						$ret = getCust($config,$idc);
						$nama = $ret['nama'];
						$kontak = '0'.$ret['no_hape'];
						$kabkot = $infopes['kabkot'];
						$prov = $infopes['prov'];
						$po = $infopes['kodepos'];
						$stat = statName($infopes['status']);
						$pesan = "Info pesanan #$nopes\nNama:$nama\nKontak:$kontak\nAlamat:$alamat\nKab/Kota:$kabkot\nProv:$prov\nPO:$po\nStatus:$stat";
						$nohp = getHPSender($config,$sender);
						if ($nohp==''){}else{
							kirimPesan($ukey,$pkey,$nohp,$pesan);
						}
						break;
				}
				$content = $twitter->get('account/verify_credentials');	//verify token
				$resp = $twitter->post('direct_messages/destroy',array('id'=>$idm));
			}
		}
	}
}
